﻿using System;
using System.Linq;

namespace MyLib {
	/// <summary>
	/// 
	/// </summary>
	public abstract class DbContextProvider {
		/// <summary>
		/// SessionFactory.
		/// </summary>
		public virtual SessionFactory SessionFactory {
			get;
			set;
		}

		/// <summary>
		/// UniqueIdGenerator.
		/// </summary>
		public virtual IUniqueIdGenerator IdGenerator {
			get;
			set;
		}

		/// <summary>
		/// 
		/// </summary>
		public DbContextProvider()
			: this(idGenerator: new GuidIdGenerator()) {
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sessionFactory"></param>
		public DbContextProvider(SessionFactory sessionFactory)
			: this(sessionFactory, new GuidIdGenerator()) {
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="idGenerator"></param>
		public DbContextProvider(IUniqueIdGenerator idGenerator)
			: this(null, idGenerator) {
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sessionFactory"></param>
		/// <param name="idGenerator"></param>
		public DbContextProvider(SessionFactory sessionFactory, IUniqueIdGenerator idGenerator) {
			System.Diagnostics.Debug.Assert(idGenerator != null);

			SessionFactory = sessionFactory;
			IdGenerator = idGenerator;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="type"></param>
		/// <param name="parameterName"></param>
		/// <param name="parameters"></param>
		/// <returns></returns>
		protected bool IsDynamicMatched(DbDynamicTextType type, string parameterName, params DbParameter[] parameters) {
			var parameter = parameters.FirstOrDefault(_p => _p.Name == parameterName);
			switch (type) {
				case DbDynamicTextType.Exists:
					return parameter != null;
				case DbDynamicTextType.NotExists:
					return parameter == null;
				case DbDynamicTextType.IsEmpty:
					if (parameter == null)
						return false;

					return parameter.Value != null && parameter.Value != DBNull.Value && parameter.Value.ToString().Length == 0;
				case DbDynamicTextType.IsNotEmpty:
					if (parameter == null)
						return false;

					return parameter.Value != null && parameter.Value != DBNull.Value && parameter.Value.ToString().Length != 0;
				case DbDynamicTextType.IsNull:
					if (parameter == null)
						return false;

					return parameter.Value == null || parameter.Value == DBNull.Value;
				case DbDynamicTextType.IsNotNull:
					if (parameter == null)
						return false;

					return parameter.Value != null && parameter.Value != DBNull.Value;
				case DbDynamicTextType.IsNullOrEmpty:
					if (parameter == null)
						return true;

					return parameter.Value == null || parameter.Value == DBNull.Value || parameter.Value.ToString().Length == 0;
				default:
					throw new InvalidProgramException("Unknown dynamic text: " + type + ".");
			}
		} // end of IsDynamicMatched.
	} // end of DbContextProvider.
}
